<template>
  <div class="article-container">
    <div class="daohang"><a @click="navigateToRoute('/repair-list-worker')">报修列表</a><span> > </span>完成报修</div>
    <hr>
    <span class="Title1">完工图片上传</span>
    <hr>
    <!-- 上传图片组件 -->
    <el-upload
      action="http://192.168.50.8:10005/repaircenter/repairFileUpload/upload"
      list-type="picture-card"
      :headers="headers"
      :auto-upload="true"
      :on-change="handleFileChange"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :file-list="uploadedImages"
    >
      <el-icon v-if="isUploadVisible">
        <Plus/>
      </el-icon>
      <template #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <el-icon><ZoomIn/></el-icon>
            </span>
            <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <el-icon><Delete/></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>

    <!-- 材料使用情况弹窗 -->
    <el-dialog v-model="materialDialogVisible" style="width: 58%;">
      <span class="materialTitle" slot="title">材料使用情况</span>
      <div></div>
      <br>
      <el-table
          :data="materials"
          border
          stripe
          :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }"
          :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
            prop="materialCode"
            label="材料编号"
            style="width: 20%"
            align="center"/>
        <el-table-column
            prop="materialName"
            label="材料名称"
            style="width: 20%"
            align="center"/>
        <el-table-column
            prop="expand1"
            label="申请数量"
            style="width: 20%"
            align="center"/>
        <el-table-column
            prop="returnedQuantity"
            label="已归还数量"
            style="width: 20%"
            align="center"
        />
        <el-table-column
            prop="count"
            label="可归还数量"
            style="width: 20%"
            align="center"/>
        <el-table-column label="归还数量" style="width: 20%">
          <template #default="scope">
            <el-input
                v-model="scope.row.returnQuantity"
                type="number"
                placeholder="请输入本次归还数量"
                @input="validateQuantity(scope.row)"
                size="small"
                :style="{ textAlign: 'center' }"
            />
          </template>
        </el-table-column>
      </el-table>

      <br>
      <span slot="footer" class="dialog-footer">
        <el-button @click="materialDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReturnMaterials">确认归还</el-button>
      </span>
    </el-dialog>
    <div>
      <hr>
      <!-- 归还材料按钮 -->
      <el-button class="materialButton" type="primary" @click="returnMaterials">归还材料</el-button>
      <!-- 完成维修按钮 -->
      <el-button class="successButton" type="success" @click="completeRepair">完成维修</el-button>
    </div>
  </div>
</template>

<script>
import { ElButton, ElUpload, ElDialog, ElTable, ElTableColumn, ElInput, ElIcon, ElMessageBox, ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  components: {
    ElButton,
    ElUpload,
    ElDialog,
    ElTable,
    ElTableColumn,
    ElInput,
    ElIcon,
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      repairId: '',
      repairNum: '',
      materials: [], // 存储查询到的材料信息
      materialDialogVisible: false, // 控制材料使用情况弹窗的显示
      materialOptions: [], // 存储材料选项
      uploadedImages: [], // 存储上传的图片
      isUploadVisible: true, // 控制上传按钮的显示状态
      disabled: false, // 控制删除按钮的显示状态
      headers: { token: localStorage.getItem('token') }
    };
  },
  created() {
    // 从路由参数中获取 repairId 和 repairNum
    this.repairId = this.$route.params.id;
    this.repairNum = this.$route.params.num;
    // 获取材料选项
    this.fetchMaterialOptions();
  },
  methods: {
    // 获取已归还数量
    getReturnedQuantity(material) {
      // 根据申请数量和可归还数量计算已归还数量
      return material.expand1 - material.count;
    },
    navigateToRoute(route){
      this.$router.push(route);
    },
    validateQuantity(row) {
      if (row.returnQuantity > row.count) {
        this.$message.warning("归还数量不能大于已归还数量");
        row.returnQuantity = row.count; // 将值重置为最大值
      } else if (row.returnQuantity < 0) {
        this.$message.warning("归还数量不能小于 0");
        row.returnQuantity = 0; // 重置为最小值
      }
    },
    // 获取材料选项
    async fetchMaterialOptions() {
      try {
        const response = await axios.get('/repaircenter/housingMaterial/getHousingMaterialList');
        if (response.data.code === 200) {
          this.materialOptions = response.data.data.map(item => ({
            value: item.materialCode,
            label: item.materialAllName
          }));
        } else {
          this.$message.error("获取材料列表失败");
        }
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('获取材料列表失败', error);
          this.$message.error("获取材料列表失败");
        }
      }
    },
    // 归还材料
    async returnMaterials() {
      try {
        const response = await axios.get('/repaircenter/repairMaterial/selectByWorkOrderNumber', {
          params: {
            repairNum: this.repairNum,
          },
          headers: {
            token: localStorage.getItem('token') // 假设 token 存储在 localStorage 中
          }
        });
        console.log('归还材料查询结果', response.data);
        if (response.data.code === 200) {
          this.materials = response.data.data.map(material => ({
            ...material,
            returnQuantity: 0, // 添加归还数量字段
            materialName: this.getMaterialName(material.materialCode), // 获取材料名称
            returnedQuantity: this.getReturnedQuantity(material) // 计算已归还数量
          })); // 存储查询到的材料信息
          this.materialDialogVisible = true; // 显示弹窗
          console.log('材料信息', this.materialDialogVisible);
        } else {
          this.$message.error("查询维修材料失败");
        }
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('归还材料查询失败', error);
          this.$message.error("归还材料查询失败");
        }
      }
    },
    // 获取材料名称
    getMaterialName(materialCode) {
      const materialOption = this.materialOptions.find(option => option.value === materialCode);
      return materialOption ? materialOption.label : '';
    },
    // 确认归还材料
    async confirmReturnMaterials() {
      try {
        const returnMaterialsData = this.materials.map(material => ({
          materialCode: material.materialCode,
          repairNum: this.repairNum,
          count: material.returnQuantity,
        }));

        const response = await axios.put('/repaircenter/repairMaterial/updateRepairMaterial', returnMaterialsData, {
          headers: {
            token: localStorage.getItem('token') // 假设 token 存储在 localStorage 中
          }
        });
        console.log('归还材料结果', response.data);
        this.$message.success("归还材料成功");
        this.materialDialogVisible = false; // 关闭弹窗
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else {
          console.error('归还材料失败', error);
          this.$message.error("归还材料失败");
        }
      }
    },
    // 上传图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片移除
    handleRemove(file) {
      console.log('handleRemove called with file:', file);
      const index = this.uploadedImages.findIndex(item => item.uid === file.uid); // 使用 uid 进行查找
      if (index !== -1) {
        this.removeImage(index);
      }
    },
    // 上传图片前的检查
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPGorPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPGorPNG && isLt2M;
    },
    // 上传图片变化处理
    handleFileChange(file, fileList) {
      if (fileList.length > 2) {
        this.$message.warning("最多只能上传 2 张图片");
        fileList.pop(); // 移除最后一个文件
        return;
      }

      // 更新 uploadedImages
      this.uploadedImages = fileList.map(f => ({
        url: f.url || URL.createObjectURL(f.raw), // 确保有 url 字段
        id: f.id || null, // 确保有 id 字段
        name: f.name,
        ...f
      }));

      // 控制上传按钮的显示状态
      if (fileList.length >= 2) {
        this.isUploadVisible = false; // 隐藏上传按钮
      } else {
        this.isUploadVisible = true; // 显示上传按钮
      }

      // 处理上传成功的文件
      fileList.forEach(f => {
        if (f.status === 'success' && f.response) {
          const repairUploadId = f.response.data[0].repairUploadId;
          const filePath = f.response.data[0].filePath;
          const index = this.uploadedImages.findIndex(item => item.uid === f.uid);
          if (index !== -1) {
            this.uploadedImages[index] = {
              ...this.uploadedImages[index],
              id: repairUploadId,
              url: filePath
            };
          }
        }
      });
    },
    // 删除图片
    removeImage(index) {
      console.log('removeImage called with index:', index);
      const imageId = this.uploadedImages[index]?.id; // 确保有 id 字段
      if (!imageId) return;

      // 移除图片 ID
      this.uploadedImages.splice(index, 1);

      // 如果图片数量小于2，重新显示上传框
      if (this.uploadedImages.length < 2) {
        this.isUploadVisible = true;
      }

      // 调用后端删除接口
      this.deleteImage(imageId);
    },
    // 删除图片接口
    deleteImage(imageId) {
      axios.delete(`http://localhost:10005/repaircenter/repairFileUpload/deleteById?id=${imageId}`)
        .then(response => {
          if (response.data.code === 200) {
            this.$message.success("图片删除成功");
          } else {
            this.$message.error("图片删除失败，请重试");
          }
        })
        .catch(error => {
          console.error('Error:', error);
          this.$message.error("图片删除失败，请重试");
        });
    },
    // 完成维修
    async completeRepair() {
      try {
        // 弹出确认框
        await ElMessageBox.confirm(
            "该操作不可取消，请确认是否已归还材料！",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
        );
        const data = {
          repairNum: this.repairNum,
          repairPhotoIds: this.uploadedImages.map(img => img.id).filter(id => id !== null) // 收集上传的图片 ID
        };
        const response = await axios.put('/repaircenter/repair/finishRepair', data, {
          headers: {
            token: localStorage.getItem('token') // 假设 token 存储在 localStorage 中
          }
        });
        console.log('完成维修结果', response.data);
        this.$message.success("完成维修成功");
        this.$router.push({ name: 'RepairListWorker' }); // 跳转回维修列表页面
      } catch (error) {
        console.log(error)
        if (error === 'ECONNABORTED') {
          this.$message.error("请求超时，请稍后再试");
        } else if (error === 'cancel') {
          console.log("用户取消了操作");
          this.$message.info("操作已取消");
        }else{
          console.error('完成维修失败', error);
          this.$message.error("完成维修失败");
        }
      }
    },
    routerHome() {
      this.$router.push('/index');
    },
  },
};
</script>

<style scoped>
.Title1 {
  font-size: 32px; /* 调整字体大小 */
  font-weight: bold; /* 加粗 */
  color: #2c3e50; /* 设置字体颜色 */
  text-align: center; /* 居中对齐 */
  margin-bottom: 20px; /* 增加下方间距 */
  font-family: 'Arial', sans-serif; /* 使用清晰的字体 */
}
.article-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin-top: 110px;
}

.daohang {
  width: 83%;
  text-align: left;
  border-bottom: 1px solid #dcdcdc;
  background: url(../assets/img/icon-location-blue.png) no-repeat 0 8px;
  background-position: 0px 0px;
  padding-left: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.daohang > a {
  color: #3498db;
  text-decoration: none;
}

.daohang > a:hover {
  text-decoration: underline;
}


.materialButton,
.successButton {
  width: 150px;
  height: 40px;
  font-size: 16px;
  border-radius: 5px;
}

.materialButton {
  background-color: #ff9800;
  border-color: #ff9800;
  color: white;
}

.materialButton:hover {
  background-color: #e68a00;
  border-color: #e68a00;
}

.successButton {
  background-color: #4caf50;
  border-color: #4caf50;
  color: white;
}

.successButton:hover {
  background-color: #45a049;
  border-color: #45a049;
}

.el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 120px;
  border: 1px dashed #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s ease;
}

.el-upload--picture-card:hover {
  border-color: #3498db;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
  border-radius: 5px;
}

.el-upload__tip {
  line-height: 1.2;
  font-size: 12px;
  color: #888;
}

.materialTitle {
  font-size: 24px;
  font-weight: bold;
  color: #34495e;
  text-align: center;
}

.el-table {
  margin: 20px 0;
}

.el-table th {
  background: #f2f4f8;
  color: #34495e;
}

.el-dialog {
  border-radius: 8px;
  padding: 10px;
  background-color: white;
}

.dialog-footer {
  text-align: right;
}


.el-dialog__header {
  font-weight: bold;
  color: #2c3e50;
}

.el-button--primary {
  background-color: #3498db;
  border-color: #3498db;
  color: white;
}

.el-button--primary:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}
</style>
